import { BrowserRouter, HashRouter, Route, Routes, } from 'react-router-dom';
import { lazy, Suspense, useEffect } from 'react';
import { v4 as uuidv4 } from 'uuid';
import dayjs from 'dayjs';
import { AuthCompoments } from './components/AuthComponents';

import Login from './pages/Login';
import Test from './pages/Test';
import NoData from './components/NoData';
import { supabase } from './utils';




//懒加载
const User = lazy(() => import('./pages/User'))
const More = lazy(() => import('./pages/User/More'))
const Message = lazy(() => import('./pages/User/Message'))
const Home = lazy(() => import('./pages/Home'))
const Register = lazy(() => import('./pages/Register'))
const MoreContent = lazy(() => import('./pages/MoreContent'))
const Search = lazy(() => import('./pages/Search'))

function App () {
  async function position(){
    let myCity = new window.BMapGL.LocalCity();
    myCity.get(async (a)=>{
      const { data, error } = await supabase
        .from('position')
        .insert([
          { id: uuidv4(), time: dayjs().format('YYYY-MM-DD HH:mm'), user:JSON.parse(localStorage.getItem('user'))?JSON.parse(localStorage.getItem('user')).username:'匿名', longitude: a.center.lng, latitude: a.center.lat, details: a.name},
        ])
    }); 
  }
  useEffect(() => {
    try {
      let geolocation = new window.BMapGL.Geolocation();
      geolocation.getCurrentPosition(async (r)=> {
        if(r!=null){
          console.log(1)
          await supabase.from('position').insert([{ id: uuidv4(), time: dayjs().format('YYYY-MM-DD HH:mm'), user:JSON.parse(localStorage.getItem('user'))?JSON.parse(localStorage.getItem('user')).username:'匿名', longitude: r.point.lng, latitude: r.point.lat, details: r.address.country + r.address.city + r.address.province + r.address.district + r.address.street }])
          return
        }
        position()
      });
    } catch (error) {
      console.log(3)
      position()
    }
  }, [])
  return (
    <HashRouter>
      <div className="App">
        <Suspense fallback={<Login />}>  
        {/* Suspense 如果组件还没有加载完成(仅支持lazy组件)。先显示fallback里面的页面 */}
          <Routes>


            <Route path='/' element={<AuthCompoments><Home /></AuthCompoments>} />

            <Route path='/search' element={<Search />} />
            <Route path='/test' element={<Test />} />  {/* 测试用 */}
            <Route path='/nodata' element={<NoData />} />{/* 暂无数据 */}
            <Route path='/login' element={<Login />} />
            <Route path='/register' element={<Register />} />
            <Route path='/user' element={<AuthCompoments><User /></AuthCompoments>}>
              <Route index element={<Message />} />
              <Route path='/user/more' element={<More />} />
            </Route>
            <Route path='/morecontent' element={<MoreContent />} />
          </Routes>


        </Suspense>
      </div>
    </HashRouter>

  );
}

export default App;